package cn.suimg.wechat.controller;

import cn.suimg.common.GeetestUtil;
import cn.suimg.common.JSONUtil;
import cn.suimg.common.request.BasicController;
import cn.suimg.common.request.RequestUtil;
import cn.suimg.common.response.ServerResponse;
import cn.suimg.wechat.bean.CorpWechat;
import cn.suimg.wechat.enmus.PublishMessageType;
import cn.suimg.wechat.service.CorpWechatService;
import cn.suimg.wechat.util.CorpWechatUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.UUID;

/**
 * 首页控制器
 * @author Suimg
 */
@Controller
@RequestMapping("/")
public class IndexController extends BasicController {


    /**
     * 推送接收用户,目前设置的是所有人 后期更新定制推送
     */
    private final String receiveInfo = JSONUtil.toString(new HashMap<String, Object>(){{
        put("touser","@all");
        put("toparty","");
        put("totag","");
    }});


    @Resource
    private CorpWechatService corpWechatService;


    @RequestMapping("index.do")
    public String index(){
        setTitle("首页");
        return "index/index";
    }

    @RequestMapping("getCaptcha.do")
    @ResponseBody
    public Object getCaptcha() {
        String captchaId;
        if ((captchaId = RequestUtil.getAttribute("captchaId")) == null) {
            captchaId = UUID.randomUUID().toString().replaceAll("-","");
            RequestUtil.setAttribute("captchaId", captchaId);
        }
        return GeetestUtil.registerChallenge(captchaId, "web", RequestUtil.getIPAddress());
    }

    @PostMapping("checkWechatInfo.do")
    @ResponseBody
    public ServerResponse checkWechatInfo(String corpId,String corpSecret,String agentId,
            @RequestParam("geetest_challenge") String challenge,
            @RequestParam("geetest_validate") String validate,
            @RequestParam("geetest_seccode") String seccode){

        //校验验证码
        if (!GeetestUtil.validateRequest(getAttribute("captchaId"), "web", getIPAddress(), challenge, validate, seccode))
            return ServerResponse.failed("验证码校验失败!");


        //初步校验信息不为空
        if(StringUtils.isBlank(corpId)||StringUtils.isBlank(corpSecret)||StringUtils.isBlank(agentId))
            return ServerResponse.failed("企业信息输入不完整");

        CorpWechat corpWechat = new CorpWechat(){{
            setCorpId(corpId);
            setCorpSecret(corpSecret);
            setAgentId(agentId);
        }};

        //尝试获取访问密钥
        CorpWechatUtil testInstance = CorpWechatUtil.getInstance(corpWechat.getCorpId(), corpWechat.getCorpSecret(), corpWechat.getAgentId());
        if(testInstance.getAccessToken() == null)
            return ServerResponse.failed("获取访问密钥失败,请检查corpId和corpSecret是否正确");

        //尝试推送一条消息
        if(!testInstance.publishMessage(receiveInfo, PublishMessageType.TextMessage,"你好,这里是推送的测试消息。如果你看到这条消息说明已经配置成功。"))
            return ServerResponse.failed("推送消息失败,请检查AgentId字段是否正确");


        String id = corpWechatService.saveCorpWechatInfo(corpWechat);

        return ServerResponse.success("保存成功",new HashMap<String, Object>(){{
            put("publishId",id);
            put("publishKey",corpWechat.getPublishKey());
            put("publishUrl","https://wx.suimg.cn:1017/publish/pkey/" + corpWechat.getPublishKey() + "/text.do");
        }});
    }
}
